import request from '@/utils/request'
import type {
  User,
  CreateUserRequest,
  UpdateUserRequest,
  Role,
  CreateRoleRequest,
  UpdateRoleRequest,
  Permission,
  CreatePermissionRequest,
  UpdatePermissionRequest,
  SystemConfig,
  CreateSystemConfigRequest,
  UpdateSystemConfigRequest,
  OperationLog,
  SystemStats,
  PaginationParams,
  PaginationResponse,
  ApiResponse,
  LoginRequest,
  LoginResponse,
  RefreshTokenResponse,
  Artist,
  CreateArtistRequest,
  UpdateArtistRequest,
  Performance,
  CreatePerformanceRequest,
  UpdatePerformanceRequest,
  Vote,
  VoteStatistics,
  FunFact,
  CreateFunFactRequest,
  UpdateFunFactRequest,
  Badge,
  CreateBadgeRequest,
  UpdateBadgeRequest,
  Venue,
  Floor,
  Activity,
  ActivityVoteStatistics,

} from '@/types'

// 认证API
export const authApi = {
  // 用户登录
  login: (data: LoginRequest) =>
    request.post<LoginResponse>('/admin/auth/login', data),

  // 用户登出
  logout: () =>
    request.post('/admin/auth/logout'),

  // 刷新令牌
  refreshToken: () =>
    request.post<RefreshTokenResponse>('/admin/auth/refresh'),

  // 获取用户信息
  getProfile: () =>
    request.get<User>('/admin/auth/profile')
}

// 用户管理API
export const userApi = {
  // 获取用户列表
  getUsers: (params?: PaginationParams & { status?: string }) =>
    request.get<PaginationResponse<User>>('/admin/users', { params }),

  // 获取用户详情
  getUser: (id: number) =>
    request.get<{ user: User }>(`/admin/users/${id}`),

  // 创建用户
  createUser: (data: CreateUserRequest) =>
    request.post<{ user: User }>('/admin/users', data),

  // 更新用户
  updateUser: (id: number, data: UpdateUserRequest) =>
    request.put<{ user: User }>(`/admin/users/${id}`, data),

  // 删除用户
  deleteUser: (id: number) =>
    request.delete(`/admin/users/${id}`),

  // 重置用户密码
  resetPassword: (id: number) =>
    request.post(`/admin/users/${id}/reset-password`),

  // 更新用户状态
  updateStatus: (id: number, status: string) =>
    request.patch(`/admin/users/${id}/status`, { status }),

  // 启用用户
  enableUser: (id: number) =>
    request.patch(`/admin/users/${id}/enable`),

  // 禁用用户
  disableUser: (id: number) =>
    request.patch(`/admin/users/${id}/disable`),

  // 获取用户统计
  getStats: () =>
    request.get<SystemStats>('/admin/users/stats'),

  // 上传头像
  uploadAvatar: (file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<User>('/admin/users/upload-avatar', formData)
  },

  // 管理员为指定用户上传头像
  uploadUserAvatar: (userId: number, file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<User>(`/admin/users/${userId}/avatar`, formData)
  },

  // 更新个人资料
  updateProfile: (data: { realName?: string; email?: string; phone?: string }) =>
    request.put<User>('/admin/users/update-profile', data),

  // 修改密码
  changePassword: (data: { currentPassword: string; newPassword: string }) =>
    request.post('/admin/users/change-password', data)
}

// 角色管理API
export const roleApi = {
  // 获取角色列表
  getRoles: (params?: PaginationParams & { status?: string }) =>
    request.get<PaginationResponse<Role>>('/admin/roles', { params }),

  // 获取角色详情
  getRole: (id: number) =>
    request.get<{ role: Role }>(`/admin/roles/${id}`),

  // 创建角色
  createRole: (data: CreateRoleRequest) =>
    request.post<{ role: Role }>('/admin/roles', data),

  // 更新角色
  updateRole: (id: number, data: UpdateRoleRequest) =>
    request.put<{ role: Role }>(`/admin/roles/${id}`, data),

  // 删除角色
  deleteRole: (id: number) =>
    request.delete(`/admin/roles/${id}`),

  // 更新角色状态
  updateStatus: (id: number, status: string) =>
    request.patch(`/admin/roles/${id}/status`, { status }),

  // 获取角色权限
  getRolePermissions: (id: number) =>
    request.get<{ permissions: Permission[] }>(`/admin/roles/${id}/permissions`),

  // 更新角色权限
  updateRolePermissions: (id: number, permissionIds: number[]) =>
    request.put(`/admin/roles/${id}/permissions`, { permissionIds }),

  // 获取角色用户
  getRoleUsers: (id: number) =>
    request.get<{ users: User[] }>(`/admin/roles/${id}/users`),

  // 分配权限
  assignPermissions: (id: number, permissionIds: number[]) =>
    request.put(`/admin/roles/${id}/permissions`, { permissionIds })
}

// 权限管理API
export const permissionApi = {
  // 获取权限列表
  getPermissions: (params?: PaginationParams & { module?: string }) =>
    request.get<PaginationResponse<Permission>>('/admin/permissions', { params }),

  // 批量创建权限
  batchCreate: (data: CreatePermissionRequest[]) =>
    request.post<{ permissions: Permission[] }>('/admin/permissions/batch', data),

  // 获取权限详情
  getPermission: (id: number) =>
    request.get<{ permission: Permission }>(`/admin/permissions/${id}`),

  // 创建权限
  createPermission: (data: CreatePermissionRequest) =>
    request.post<{ permission: Permission }>('/admin/permissions', data),

  // 更新权限
  updatePermission: (id: number, data: UpdatePermissionRequest) =>
    request.put<{ permission: Permission }>(`/admin/permissions/${id}`, data),

  // 删除权限
  deletePermission: (id: number) =>
    request.delete(`/admin/permissions/${id}`),

  // 获取权限树
  getPermissionTree: () =>
    request.get<{ permissions: Permission[] }>('/admin/permissions/tree'),

  // 获取权限模块
  getModules: () =>
    request.get<{ modules: string[] }>('/admin/permissions/modules'),

  // 获取权限树
  getTree: () =>
    request.get<{ tree: Permission[] }>('/admin/permissions/tree')
}

// 艺人管理API
export const artistApi = {
  // 获取艺人列表
  getList: (params?: PaginationParams & { search?: string }) =>
    request.get<PaginationResponse<Artist>>('/admin/artists', { params }),

  // 获取艺人详情
  get: (id: number) =>
    request.get<Artist>(`/admin/artists/${id}`),

  // 创建艺人
  create: (data: CreateArtistRequest) =>
    request.post<ApiResponse<Artist>>('/admin/artists', data),

  // 更新艺人
  update: (id: number, data: UpdateArtistRequest) =>
    request.put<ApiResponse<Artist>>(`/admin/artists/${id}`, data),

  // 删除艺人
  delete: (id: number) =>
    request.delete(`/admin/artists/${id}`),

  // 上传艺人头像
  uploadAvatar: (id: number, file: File) => {
    const formData = new FormData()
    formData.append('avatar', file)
    return request.post<ApiResponse<Artist>>(`/admin/artists/${id}/avatar`, formData)

  },

  // 上传艺人横幅
  uploadBanner: (id: number, file: File) => {
    const formData = new FormData()
    formData.append('bannerImage', file)
    return request.post<ApiResponse<Artist>>(`/admin/artists/${id}/banner`, formData)

  }
}

// 演出管理API
export const performanceApi = {
  // 获取演出列表
  getList: (params?: PaginationParams & { search?: string; status?: string; date?: string; venueId?: number }) =>
    request.get<PaginationResponse<Performance>>('/admin/performances', { params }),

  // 获取演出详情
  get: (id: number) =>
    request.get<Performance>(`/admin/performances/${id}`),

  // 创建演出
  create: (data: CreatePerformanceRequest) =>
    request.post<ApiResponse<Performance>>('/admin/performances', data),

  // 更新演出
  update: (id: number, data: UpdatePerformanceRequest) =>
    request.put<ApiResponse<Performance>>(`/admin/performances/${id}`, data),

  // 删除演出
  delete: (id: number) =>
    request.delete(`/admin/performances/${id}`)
}

// 场地管理API
export const venueApi = {
  // 获取场地列表
  getList: (params?: PaginationParams & { search?: string; status?: string }) =>
    request.get<PaginationResponse<Venue>>('/admin/venues', { params }),

  // 获取场地详情
  get: (id: number) =>
    request.get<Venue>(`/admin/venues/${id}`),

  // 创建场地
  create: (data: any) =>
    request.post<ApiResponse<Venue>>('/admin/venues', data),

  // 更新场地
  update: (id: number, data: any) =>
    request.put<ApiResponse<Venue>>(`/admin/venues/${id}`, data),

  // 删除场地
  delete: (id: number) =>
    request.delete(`/admin/venues/${id}`)
}

// 楼层管理API
export const floorApi = {
  // 根据场地ID获取楼层列表
  getByVenue: (venueId: number) =>
    request.get<Floor[]>(`/admin/venues/${venueId}/floors`),

  // 获取楼层详情
  get: (id: number) =>
    request.get<Floor>(`/admin/floors/${id}`),

  // 创建楼层
  create: (data: any) =>
    request.post<ApiResponse<Floor>>('/admin/floors', data),

  // 更新楼层
  update: (id: number, data: any) =>
    request.put<ApiResponse<Floor>>(`/admin/floors/${id}`, data),

  // 删除楼层
  delete: (id: number) =>
    request.delete(`/admin/floors/${id}`)
}

// 系统管理API
export const systemApi = {
  // 系统配置
  config: {
    // 获取配置列表
    getList: (params?: PaginationParams & { type?: string }) =>
      request.get<PaginationResponse<SystemConfig>>('/admin/system/configs', { params }),

    // 获取配置详情
    getById: (id: number) =>
      request.get<{ config: SystemConfig }>(`/admin/system/configs/${id}`),

    // 创建配置
    create: (data: CreateSystemConfigRequest) =>
      request.post<{ config: SystemConfig }>('/admin/system/configs', data),

    // 更新配置
    update: (id: number, data: UpdateSystemConfigRequest) =>
      request.put<{ config: SystemConfig }>(`/admin/system/configs/${id}`, data),

    // 删除配置
    delete: (id: number) =>
      request.delete(`/admin/system/configs/${id}`),

    // 批量更新配置
    batchUpdate: (configs: UpdateSystemConfigRequest[]) =>
      request.put('/admin/system/configs/batch', { configs })
  },

  // 系统统计
  stats: () =>
    request.get<SystemStats>('/admin/system/stats'),

  // 缓存管理
  cache: {
    // 清除缓存
    clear: (data: {
      type: 'all' | 'prefix' | 'pattern'
      prefix?: string
    }) => request.post('/admin/system/cache/clear', data),

    // 获取缓存统计信息
    getStats: () => request.get('/admin/system/cache/stats'),

    // 预热缓存
    warmup: (data: {
      type: 'system_config' | 'user_permissions'
    }) => request.post('/admin/system/cache/warmup', data),

    // 获取缓存键列表
    getKeys: (params?: {
      pattern?: string
      limit?: number
    }) => request.get('/admin/system/cache/keys', { params })
  }
}

// 日志管理API
export const logApi = {
  // 获取日志列表
  getList: (params?: PaginationParams & { 
    userId?: number, 
    action?: string, 
    resource?: string,
    startDate?: string, 
    endDate?: string,
    search?: string,
    ipAddress?: string,
    sortBy?: string,
    sortOrder?: string
  }) =>
    request.get<PaginationResponse<OperationLog>>('/admin/logs', { params }),

  // 获取日志详情
  getById: (id: number) =>
    request.get<OperationLog>(`/admin/logs/${id}`),

  // 清空日志
  clear: (beforeDate?: string) =>
    request.delete('/admin/logs/clear', { data: { beforeDate } }),

  // 获取日志统计
  getStats: (params?: { startDate?: string, endDate?: string }) =>
    request.get<any>('/admin/logs/stats', { params }),

  // 获取日志分析
  getAnalytics: (params?: { startDate?: string, endDate?: string }) =>
    request.get<any>('/admin/logs/analytics', { params }),

  // 导出日志
  export: (params?: { 
    format?: string, 
    startDate?: string, 
    endDate?: string,
    userId?: number,
    action?: string,
    resource?: string,
    search?: string
  }) =>
    request.get<any>('/admin/logs/export', { params })
}



// 投票管理API
export const voteApi = {
  // 获取投票统计
  getStatistics: (params?: { startDate?: string, endDate?: string, artistId?: number }) =>
    request.get<VoteStatistics>('/admin/votes/statistics', { params }),

  // 获取投票列表
  getList: (params?: PaginationParams & { artistId?: number, userId?: number }) =>
    request.get<PaginationResponse<Vote>>('/admin/votes', { params }),

  // 删除投票记录
  delete: (id: number) =>
    request.delete(`/admin/votes/${id}`),

  // 重置投票数据
  reset: () =>
    request.post('/admin/votes/reset')
}

// 活动管理API
export const activityApi = {
  // 获取活动列表
  getList: (params?: PaginationParams & { 
    status?: string; 
    search?: string 
  }) =>
    request.get<PaginationResponse<Activity>>('/admin/activities', { params }),

  // 获取活动详情
  getDetail: (id: number) =>
    request.get<Activity>(`/admin/activities/${id}`),

  // 创建活动
  create: (data: Partial<Activity>) =>
    request.post<Activity>('/admin/activities', data),

  // 更新活动
  update: (id: number, data: Partial<Activity>) =>
    request.put<Activity>(`/admin/activities/${id}`, data),

  // 删除活动
  delete: (id: number) =>
    request.delete(`/admin/activities/${id}`),

  // 添加艺人到活动
  addArtist: (data: { 
    activityId: number; 
    artistId: number; 
    sortOrder?: number 
  }) =>
    request.post(`/admin/activities/${data.activityId}/artists`, data),

  // 从活动移除艺人
  removeArtist: (activityId: number, artistId: number) =>
    request.delete(`/admin/activities/${activityId}/artists/${artistId}`),

  // 更新活动艺人排序
  updateArtistOrder: (activityId: number, data: { 
    artists: Array<{ artistId: number; sortOrder: number }> 
  }) =>
    request.put(`/admin/activities/${activityId}/artists/order`, data),

  // 获取活动投票统计
  getVoteStatistics: (id: number) =>
    request.get<ActivityVoteStatistics>(`/admin/activities/${id}/statistics`)
}

// 内容管理API
export const contentApi = {
  // 冷知识管理
  funFacts: {
    // 获取冷知识列表
    getList: (params?: PaginationParams & { isActive?: boolean }) =>
      request.get<PaginationResponse<FunFact>>('/admin/content/trivia', { params }),

    // 获取冷知识详情
    getById: (id: number) =>
      request.get<{ funFact: FunFact }>(`/admin/content/trivia/${id}`),

    // 创建冷知识
    create: (data: CreateFunFactRequest) =>
      request.post<{ funFact: FunFact }>('/admin/content/trivia', data),

    // 更新冷知识
    update: (id: number, data: UpdateFunFactRequest) =>
      request.put<{ funFact: FunFact }>(`/admin/content/trivia/${id}`, data),

    // 删除冷知识
    delete: (id: number) =>
      request.delete(`/admin/content/trivia/${id}`)
  },

  // 徽章管理
  badges: {
    // 获取徽章列表
    getList: (params?: PaginationParams & { type?: string }) =>
      request.get<PaginationResponse<Badge>>('/admin/content/badges', { params }),

    // 获取徽章详情
    getById: (id: number) =>
      request.get<{ badge: Badge }>(`/admin/content/badges/${id}`),

    // 创建徽章
    create: (data: CreateBadgeRequest) =>
      request.post<{ badge: Badge }>('/admin/content/badges', data),

    // 更新徽章
    update: (id: number, data: UpdateBadgeRequest) =>
      request.put<{ badge: Badge }>(`/admin/content/badges/${id}`, data),

    // 删除徽章
    delete: (id: number) =>
      request.delete(`/admin/content/badges/${id}`),

    // 上传徽章图标
    uploadIcon: (id: number, file: File) => {
      const formData = new FormData()
      formData.append('badgeIcon', file)
      return request.post<{ badge: Badge; iconUrl: string }>(`/admin/content/badges/${id}/icon`, formData)
    },

    // 删除徽章图标
    deleteIcon: (id: number) =>
      request.delete<{ badge: Badge }>(`/admin/content/badges/${id}/icon`)
  },


}

// 楼层管理
export * from './floor';